package com.itheima.service.impl;

import com.itheima.entity.OrderDetail;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.OrderDetailMapper;
import com.itheima.service.OrderDetailService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单详情实现类
 */
@Service
@Transactional
@Slf4j
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 循环遍历插入订单详情表
     * 传入订单id
     * 1.根据当前用户id查询购物车数据
     * 2.将购物车数据copy到订单详情表中
     * 3.循环插入orderDetail表中
     * @param ordersId
     */
    @Override
    public void insert(Long ordersId) {
        //1.根据当前用户id查询购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.list();
        //2.将购物车数据copy到订单详情表中
        if(!CollectionUtils.isEmpty(shoppingCartList)) {
            //购物车数据进行遍历
            shoppingCartList.stream().map(
                    shoppingCart ->{
                        //shoppingCart 购物车每一条记录
                        OrderDetail orderDetail = new OrderDetail();
                        //从购物车对象中copy数据到订单详情中
                        BeanUtils.copyProperties(shoppingCart,orderDetail);
                        //设置orderDetail表中订单id
                        orderDetail.setOrderId(ordersId);//订单id
                        //将orderDetail插入表中
                        orderDetailMapper.insert(orderDetail);
                        log.debug("**循环插入订单详情表成功了**");
                        return orderDetail;
                    }
                    //3.循环插入orderDetail表中
            ).collect(Collectors.toList());
        }

        //3 清除当前用户购物车数据
        shoppingCartService.clean();
        log.debug("**清空购物车成功了**");
    }
}
